﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tilver.Configuration;
using Tilver.Common;

namespace Tilver.Data
{
    /// <summary>
    /// 数据库操作基类
    /// </summary>
    public class DbManagerBase
    {
        private static object _lock = new object();
        private static DbRouterBase _router;
        public DbDataBase DataBase { get; internal set; }

        protected DbManagerBase(string connectionStringName) : this(DbDataFactory.Create(connectionStringName)) { }

        protected DbManagerBase(DbDataBase dataBase)
        {
            DataBase = dataBase;
        }
        protected DbManagerBase(object routeData)
        {
            //调用路由操作基类的方法
            var router = GetRouter();
            //DataBase = router.RouteDataBase(type, routeData);
            DataBase = router.RouteDataBase(this.GetType(), routeData);
        }

        /// <summary>
        /// 获取数据访问路由
        /// </summary>
        /// <returns></returns>
        private static DbRouterBase GetRouter()
        {
            if (_router == null)
            {
                lock (_lock)
                {
                    if (_router == null)
                    {
                        //检查data配置节dataRouterProvider属性是否指定了数据访问路由
                        var section = TilverSection.GetSection("tilver");
                        if ((section != null) && !string.IsNullOrEmpty(section.DataConfig.DataRouterProvider))
                        {
                            _router = (DbRouterBase)DynamicCompiler.CreateBuilder(section.DataConfig.DataRouterProvider, false)();
                        }
                        else
                        {
                            _router = new DbRouterBase();
                        }
                    }
                }
            }
            return _router;
        }
    }
}
